'use client';

import React, { useEffect, useMemo, useState, useContext } from 'react';
import dynamic from 'next/dynamic';
import { getCommunityTimeSeries, TimeSeriesPoint } from '@/services/api';
import { TimeContext, SIMULATION_START_TIME } from '@/context/TimeContext';
import { DataContext } from '@/context/DataContext';
import { formatUTCDate } from '@/lib/utils';
import { useRef } from 'react';

const ReactECharts = dynamic(() => import('echarts-for-react'), { ssr: false });

interface Props {
  communityId: number;
  communityName?: string;
  onClose: () => void;
}

const CUMULATIVE_START_TIME = new Date('2021-05-01T00:00:00Z');

export default function CommunityPanel({ communityId, communityName, onClose }: Props) {
  const { currentTime } = useContext(TimeContext)!;
  const dataCtx = useContext(DataContext)!;

  const [loading, setLoading] = useState(false);
  const [series, setSeries] = useState<TimeSeriesPoint[]>([]);
  const [error, setError] = useState<string | null>(null);

  const lastRequestRef = useRef<{ id: number; time: string } | null>(null);

  // 计算当前时间槽的预测剩余单车数（与地图相同公式）
  const remainingBikes = useMemo(() => {
    if (!dataCtx) return 0;
    const { initialCounts, historicalFlows, predictedFlows } = dataCtx;

    const initial = initialCounts[communityId] ?? 0;

    let cumulativeFlow = 0;
    let slot = new Date(CUMULATIVE_START_TIME);
    while (slot < currentTime) {
      const key = slot.toISOString();
      cumulativeFlow += historicalFlows[communityId]?.[key] || 0;
      slot.setMinutes(slot.getMinutes() + 30);
    }
    const currKey = currentTime.toISOString();
    const predicted = predictedFlows[communityId]?.[currKey] || 0;

    return Math.floor(initial + cumulativeFlow + predicted);
  }, [dataCtx, communityId, currentTime]);

  // 计算“当前时间对齐到槽起点”的时间（用作接口查询 time）
  const alignedSlotISO = useMemo(() => {
    const d = new Date(currentTime);
    const minute = d.getUTCMinutes();
    const startMinute = minute >= 30 ? 30 : 0;
    d.setUTCMinutes(startMinute, 0, 0);
    return d.toISOString();
  }, [currentTime]);

  // 拉取 24h 借/还曲线
  useEffect(() => {

    if (
      lastRequestRef.current &&
      lastRequestRef.current.id === communityId &&
      lastRequestRef.current.time === alignedSlotISO
    ) {
      return;
    }

    let mounted = true;
    const fetchData = async () => {
      setLoading(true);
      setError(null);
      lastRequestRef.current = { id: communityId, time: alignedSlotISO };
      const res = await getCommunityTimeSeries(communityId, alignedSlotISO);
      if (!mounted) return;
      if (!res) {
        setError('获取时序数据失败');
        setSeries([]);
      } else {
        setSeries(res.series ?? []);
      }
      setLoading(false);
    };
    fetchData();
    return () => { mounted = false; };
  }, [communityId, alignedSlotISO]);

  // 将后端时间槽（无Z）转成显示标签 HH:mm
  const xData = useMemo(() => {
    return series.map(p => {
      const d = new Date(p.time_slot + 'Z'); // 强制按 UTC 解析
      const hh = String(d.getUTCHours()).padStart(2, '0');
      const mm = String(d.getUTCMinutes()).padStart(2, '0');
      return `${hh}:${mm}`;
    });
  }, [series]);

  const borrow = series.map(p => p.borrow_count);
  const ret = series.map(p => p.return_count);

  const option = useMemo(() => ({
    backgroundColor: 'transparent',
    grid: { left: 48, right: 24, top: 40, bottom: 32 },
    tooltip: { 
      trigger: 'axis',
     },
    legend: { data: ['借车', '还车'], textStyle: { color: '#ddd' } },
    top: 10,
    right: 20,
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: { color: '#bbb' },
      axisLine: { lineStyle: { color: '#666' } },
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#bbb' },
      splitLine: { lineStyle: { color: 'rgba(255,255,255,0.08)' } },
    },
    series: [
      {
        name: '借车',
        type: 'line',
        smooth: true,
        data: borrow,
        showSymbol: false,
        lineStyle: { color: '#e74c3c' },
        areaStyle: { color: 'rgba(231,76,60,0.15)' },
      },
      {
        name: '还车',
        type: 'line',
        smooth: true,
        data: ret,
        showSymbol: false,
        lineStyle: { color: '#3498db' },
        areaStyle: { color: 'rgba(52,152,219,0.15)' },
      },
    ],
  }), [xData, borrow, ret]);

  return (
    <div className="w-[420px] bg-gray-900/90 border border-gray-700 rounded-lg shadow-2xl backdrop-blur-md text-gray-100 m-2">
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-700">
        <div className="font-semibold">
          {communityName ?? `社区 ${communityId}`}
        </div>
        <button
          onClick={onClose}
          className="text-gray-300 hover:text-white px-2 py-1 rounded hover:bg-gray-700"
        >
          关闭
        </button>
      </div>

      <div className="px-4 py-3 text-sm text-gray-300">
        <div className="flex items-center justify-between">
          <span>当前时间</span>
          <span className="font-mono">{formatUTCDate(currentTime)}</span>
        </div>
        <div className="flex items-center justify-between mt-1">
          <span>预测剩余单车数</span>
          <span className="font-mono text-blue-300">{remainingBikes}</span>
        </div>
      </div>

      <div className="px-2 pb-3">
        {loading ? (
          <div className="p-6 text-center text-gray-400">加载中...</div>
        ) : error ? (
          <div className="p-6 text-center text-red-400">{error}</div>
        ) : (
          <ReactECharts
            option={option}
            notMerge
            lazyUpdate
            style={{ height: 280 }}
          />
        )}
      </div>
    </div>
  );
}